package com.moyun.zbmy.zizhou.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.Gson;
import com.jiongbull.jlog.JLog;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.application.Constances;
import com.moyun.zbmy.zizhou.base.BaseActivity;
import com.moyun.zbmy.zizhou.beans.AFileItem;
import com.moyun.zbmy.zizhou.beans.FocusColumn;
import com.moyun.zbmy.zizhou.beans.HomeListItem;
import com.moyun.zbmy.zizhou.beans.HomeLive;
import com.moyun.zbmy.zizhou.beans.LiveItem;
import com.moyun.zbmy.zizhou.beans.NewsClickCountBean;
import com.moyun.zbmy.zizhou.beans.NewsIdBean;
import com.moyun.zbmy.zizhou.beans.NewsItem;
import com.moyun.zbmy.zizhou.beans.NewsListClickRequestBean;
import com.moyun.zbmy.zizhou.beans.NewsListClickVo;
import com.moyun.zbmy.zizhou.beans.SearchResult;
import com.moyun.zbmy.zizhou.beans.SingleResult;
import com.moyun.zbmy.zizhou.beans.SubscriptionNoBean;
import com.moyun.zbmy.zizhou.beans.SubscriptionNoListBean;
import com.moyun.zbmy.zizhou.beans.TopicItem;
import com.moyun.zbmy.zizhou.http.AbsListNetCallback;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.ui.adapter.NewListAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.SearchResultAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.SubscriptionNoAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.holder.HomeLiveHolder;
import com.moyun.zbmy.zizhou.ui.util.IListShowData;
import com.moyun.zbmy.zizhou.ui.utils.KeyBoardUtils;
import com.moyun.zbmy.zizhou.ui.utils.TitleUtils;
import com.moyun.zbmy.zizhou.utils.ListTypeUtils;
import com.ruihang.generalibrary.utils.ListUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 部门乡镇搜索（搜索订阅号、新闻）
 */
public class SearchSubscriptionNoNewsActivity extends BaseActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener
        , SubscriptionNoAdapter.OnSubscriptionNoClickListener {

    @BindView(R.id.input_key)
    protected EditText searchKey;
    @BindView(R.id.search_result_layout)
    protected LinearLayout searchResultLayout;
    @BindView(R.id.search_null_layout)
    protected RelativeLayout searchNullLayout;
    @BindView(R.id.refresh_layout)
    protected CanRefreshLayout mRefreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;

    private String inputKey;
    private NewListAdapter adapter;
    private int mPageNo = 0;
    private boolean mIsLoading = false;
    private int mPageAll = 0;
    private List<IListShowData> dataList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_search_subscription_no_news);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initView() {
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRefreshLayout.setLoadMoreEnabled(false);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        searchKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = searchKey.getText().toString().trim();
//                if (TextUtils.isEmpty(str)) {
//                    cleanBtn.setVisibility(View.GONE);
//                } else {
//                    cleanBtn.setVisibility(View.VISIBLE);
//                }
            }
        });
    }

    @Override
    public void onLoadMore() {
        mPageNo++;
        search();
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        dataList.clear();
        mPageNo = 0;
        mIsLoading = true;
        searchData();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            inputKey = searchKey.getText().toString().trim();
            if (TextUtils.isEmpty(inputKey)) {
                toast("请输入关键词");
            } else {
                //TODO  搜索
                mRefreshLayout.autoRefresh();
            }
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 搜索订阅号
     */
    private void searchData() {

        NetUtils.getNetAdapter().searchSubscriptionNoList(getOwnerName(), inputKey, new AbsListNetCallback<SubscriptionNoBean>(ListTypeUtils.SubscriptionNoBean(), 0) {
            @Override
            public void onSuc(List<SubscriptionNoBean> list) {
                if (ListUtils.isListValued(list)) {
                    SubscriptionNoListBean noListBean = new SubscriptionNoListBean();
                    noListBean.setSubscriptionNoList(list);
                    noListBean.setViewType(NewListAdapter.VIEWTYPE_SUBSCRIPTION_NO_LIST);
                    noListBean.setShowBottom(true);
                    dataList.add(noListBean);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(errorMsg);

            }

            @Override
            public void onEnd() {
                onNetFinish();
                mIsLoading = false;
                search();
            }
        });
    }

    /**
     * 搜索关键词相关新闻
     */
    private void search() {
        KeyBoardUtils.closeKeyboard(this);
        ArrayMap<String, Object> param = new ArrayMap<>();
        param.put("keyword", inputKey);
        param.put("siteNumber", Constances.SITE_ID);
        param.put("index", mPageNo);
        param.put("option", 5);
        param.put("count", 10);
        NetUtils.getNetAdapter().keywordOptionSearchFulltext(getOwnerName(), param, new AbsNetCallBack<SearchResult>(SearchResult.class) {
            @Override
            public void onSuc(SearchResult fSearch) {
                if (fSearch != null && (ListUtils.isListValued(fSearch.getAnchorList()) || ListUtils.isListValued(fSearch.getLiveList()) || ListUtils.isListValued(fSearch.getNewsList()) || ListUtils.isListValued(fSearch.getSpecialList()))) {
                    JLog.e("=====search==" + fSearch.toString());
                    setSearchData(fSearch);
                }

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                if (mPageNo > 1) {
                    mPageNo--;
                }
                toast(errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
                initData();
            }
        });
    }

    /**
     * 赋值显示搜索结果
     *
     * @param fSearches
     */
    private void setSearchData(SearchResult fSearches) {
        List<NewsItem> newsList = fSearches.getNewsList();
//        List<FProgram> programmeList = fSearches.getProgrammeList();
//        List<LiveItem> liveList = fSearches.getLiveList();
//        List<AFileItem> anchorList = fSearches.getAnchorList();
//        List<TopicItem> specialList = fSearches.getSpecialList();
        List<IListShowData> tempList = new ArrayList<>();

        if (ListUtils.isListValued(newsList)) {
            if (newsList.size() >= 10) {
                mRefreshLayout.setLoadMoreEnabled(true);
            } else {
                mRefreshLayout.setLoadMoreEnabled(false);
            }
            for (int i = 0; i < newsList.size(); i++) {
                newsList.get(i).setViewType(NewListAdapter.VIEWTYPE_NEWS);
            }
            dataList.addAll(newsList);
        } else {
            mRefreshLayout.setLoadMoreEnabled(false);
        }
    }

    private void initData() {
        if (null == adapter) {
            adapter = new NewListAdapter(this, dataList);
            mRecyclerView.setAdapter(adapter);
            adapter.setSubscriptionNoClickListener(this);
            adapter.notifyDataSetChanged();
        } else {
            adapter.setData(dataList);
        }

        if (ListUtils.isListValued(dataList)) {
            searchResultLayout.setVisibility(View.VISIBLE);
            searchNullLayout.setVisibility(View.GONE);
        } else {
            searchResultLayout.setVisibility(View.GONE);
            searchNullLayout.setVisibility(View.VISIBLE);
        }
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        mRefreshLayout.refreshComplete();
        mRefreshLayout.loadMoreComplete();

    }

    @Override
    public void OnSubscriptionNoClick(SubscriptionNoBean bean) {
        //TODO 点击公众号
        Intent intent = new Intent(this, SubscriptionNoDetailActivity.class);
        intent.putExtra(SubscriptionNoDetailActivity.SUBSCRIPTION_NO_ID, bean.getWxId());
        intent.putExtra(BaseActivity.EX_TITLE, bean.getWxName());
        startActivity(intent);
    }


    @OnClick(value = {R.id.cancel})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.cancel:
                finish();
                break;

        }
    }


}
